package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        if(dto==null){
            //数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据为空");
        }
        //1.检查参数
        if (StringUtils.isBlank(dto.getName())) {
            //获取的登录名为空,抛出登录名或者密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //2.查询用户
        WmUser wmUser =getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,dto.getName()));
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户数据不存在!");
        }
        //3.比对密码
        //先获取数据库数据
        String salt = wmUser.getSalt();
        //传入的密码
        String password = dto.getPassword();
        //密码的拼装
        password=DigestUtils.md5DigestAsHex((password+salt).getBytes(StandardCharsets.UTF_8));
        if(password.equals(wmUser.getPassword())){
            //密码正确,返回JWT 类型数据
            Map<String,Object>map=new HashMap<>();
            //数据是键值对类型
            map.put("token",AppJwtUtil.getToken(wmUser.getId().longValue()));
            //返回给前端的数据,需要对敏感数据处理
            wmUser.setSalt("");
            wmUser.setPassword("");
            map.put("user",wmUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}